package core

import (
	"fmt"
	"net/http"
	"os"
	"path"
	//_ "net/http/pprof"
)

func serveFile(prefix, root string) {
	http.HandleFunc(prefix, func(writer http.ResponseWriter, request *http.Request) {
		//检验是否是文件
		url := request.RequestURI
		filePath := fmt.Sprintf("%s%s", root, url)
		fileInfo, e := os.Stat(fmt.Sprintf("%s%s", root, url))
		if os.IsNotExist(e) || fileInfo.IsDir() {
			//不是文件,读取首页
			filePath = fmt.Sprintf("%s/index.html", root)
			writer.Header().Set("Content-Type", "text/html; charset=utf-8")
		} else {
			if !os.IsNotExist(e) {
				writer.Header().Set("Cache-Control", "public, max-age=31536000")
				if path.Ext(fileInfo.Name()) == ".css" {
					//content-type: text/css
					writer.Header().Set("Content-Type", "text/css")
				}
				if path.Ext(fileInfo.Name()) == ".js" {
					//content-type: text/css
					writer.Header().Set("Content-Type", "application/javascript")
				}
			}
		}
		content, e := os.ReadFile(filePath)
		if e != nil {
			println(e.Error())
		}
		_, e = writer.Write(content)
		if e != nil {
			println(e.Error())
		}
	})
}
